# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2015 Jeafea (<1062042200@qq.com>)
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
import logging


class SaleOrder(models.Model):
    _inherit = "sale.order"

    @api.one
    @api.depends('order_line.agents.amount')
    def _get_commission_total(self):
        self.commission_total = 0.0
        for line in self.order_line:
            self.commission_total += sum(x.amount for x in line.commission_item)

    agents = fields.Many2many('res.partner',related='partner_id.agents')
    commission_plan_id = fields.Many2many('commission.plan')
    commission_total = fields.Float(
        string="Commissions",
        store=True)

    @api.one
    @api.onchange('partner_id')
    def onchange_partner(self):
        print '15555'
        if self.partner_id:
            print '2323'
            for agent in self.partner_id.agents:
                print '3222'
                print agent
                self.agents = agent
                logging.warning(u'也滚进去')
                for plan in agent.plan_id:
                    logging.warning(u'也滚进22去')
                    self.commission_plan_id = plan.id

class SaleOrderLine(models.Model):
    _inherit = "sale.order.line"

    @api.model
    def _default_agents(self):
        agents = []
        if self.env.context.get('partner_id'):
            partner = self.env['res.partner'].browse(
                self.env.context['partner_id'])
            for agent in partner.agents:
                agents.append({'agent': agent.id,
                               'commission': agent.commission.id})
        return [(0, 0, x) for x in agents]

    @api.model
    def _prepare_order_line_invoice_line(self, line, account_id=False):
        vals = super(SaleOrderLine, self)._prepare_order_line_invoice_line(
            line, account_id=account_id)
        vals['agents'] = [
            (0, 0, {'agent': x.agent.id,
                    'commission': x.commission.id}) for x in line.agents]
        return vals

    commission_item = fields.One2many('sale.commission.item','order_line')

class SaleCommissionItem(models.Model):
    _name = "sale.commission.item"

    name = fields.Text()
    product_id = fields.Many2one('product.product',related="order_line.product_id")
    order_line = fields.Many2one('sale.order.line',ondelete="cascade")
    partner_id = fields.Many2one('res.partner',related="order_line.order_id.partner_id")
    agents = fields.Many2one('res.partner')
    plan_id = fields.Many2one('commission.plan')
    commission_item_id = fields.Many2one('commission.version.item')
    price_unit = fields.Float()
    discount = fields.Float()
    product_uom_qty = fields.Float()
    subtotal_amount = fields.Float()
    note = fields.Text()

    @api.one
    @api.onchange('agent')
    def onchange_agent(self):
        self.commission = self.agent.commission

    @api.one
    @api.depends('commission.commission_type', 'sale_line.price_subtotal')
    def _get_amount(self):
        self.amount = 0.0
        if (not self.sale_line.product_id.commission_free and
                self.commission):
            subtotal = self.sale_line.price_subtotal
            if self.commission.commission_type == 'fixed':
                self.amount = subtotal * (self.commission.fix_qty / 100.0)
            else:
                self.amount = self.commission.calculate_section(subtotal)
